package com.baizhi.action;

import com.baizhi.entity.User;
import com.baizhi.service.UserService;
import com.baizhi.service.impl.UserServiceImpl;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class UserAction {
    private User user;
    private UserService service = new UserServiceImpl();
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    //测试ajax请求
    public void test() throws IOException {
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter pw = response.getWriter();
        pw.print("OK");
        pw.flush();
    }

    public void login(){
        System.out.println("登陆收参"+user.getUsername());
        boolean login = service.login(user.getUsername(), user.getPassword());
        System.out.println(login);
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            if(login){
                pw.print(0);
            }else{
                pw.print(1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.flush();
        }
    }
    public void getOneUser(){
        User u = service.selectByUsername(user.getUsername());
        System.out.println(u);
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            if(u!=null){
                pw.print(0);
            }else{
                pw.print(1);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            pw.flush();
        }
    }
    public void register(){
        HttpServletResponse response = ServletActionContext.getResponse();
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            service.register(user);
            pw.print(0);
        } catch (IOException e) {
            pw.print(1);
            e.printStackTrace();
        } finally {
            pw.flush();
        }
    }
}
